<template>
  <el-dialog v-model="dialogVisible" :title="title">
    <BaseForm @cancel='handleCancel' @submit='handleSubmit' :data='data' :fields='fields'>
      <!-- 远程搜索商品名称 -->
      <template v-slot:goodsId='{item:data}'>
        <el-autocomplete
          v-model="data.goodsName"
          :fetch-suggestions="querySearchAsync"
          placeholder="Please input"
          @select="handleSelect($event,data)"
          style='width:100%'
        >
          <template v-slot:default='{item}'>
            <div>
              <span>商品编号：{{item.id}}</span>
              <span class='ml-8 mr-8'>品牌：{{item.brand}}</span>
              <span>商品名称：{{item.name}}</span>
            </div>
          </template>
        </el-autocomplete>
      </template>
      <!-- 商品数量 -->
      <template v-slot:count='{item}'>
        <el-input-number v-model="item.count" :min="1" :precision="0" :controls='false' @change="handleChange($event,item)" />
      </template>
      <!-- 出售价格 -->
      <template v-slot:salePrice='{item}'>
        <el-form-item
        v-if='item.status< 1'
          label="出售价格"
          prop="salePrice"
        >
          <el-input-number v-model="item.salePrice" :min="1" :precision="2" :controls='false' />
        </el-form-item>
      </template>
    </BaseForm>
  </el-dialog>
</template>

<script lang='ts'>

import { computed, defineComponent, ref, watchEffect } from '@vue/runtime-core'
import BaseForm from '@/components/form/base/index.vue'
import { ElMessage } from 'element-plus'
import { getClassesList } from '@/api/classes'
import { orderCreate, orderEdit } from '@/api/order'
import { getGoodsList } from '@/api/goods'
import { useStore } from 'vuex'
import { RootStore } from '@/store'
export default defineComponent({
  name: 'UserForm',
  props: {
    data: {
      type: Object,
      default: () => ({}),
    },
    visible: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: '',
    },
  },
  components: {
    BaseForm,
  },
  emits: ['update:visible', 'refresh'],
  setup (props, { emit }) {
    // const dialogVisible = ref(false)
    const store = useStore<RootStore>()
    const options = ref([])

    watchEffect(async () => {
      if (props.visible) {
        const data = await getClassesList() as any
        options.value = data.rows.map(item => ({ ...item, id: String(item.id) })) || []
      }
    })

    const dialogVisible = computed({
      get () {
        return props.visible
      },
      set (value) {
        emit('update:visible', value)
      },
    })
    const fields = [

      {
        value: 'goodsId',
        label: '商品名称',
        slot: true,
      },
      {
        value: 'goodsBrand',
        label: '品牌',
        props: {
          disabled: true,
        },
      },
      {
        value: 'unit',
        label: '单位',
        props: {
          disabled: true,
        },
      },
      {
        value: 'weight',
        label: '商品规格',
        props: {
          disabled: true,
        },
      },
      {
        value: 'price',
        label: '商品价格',
        props: {
          disabled: true,
        },
      },
      {
        value: 'totalFee',
        label: '订单总价',
        props: {
          disabled: true,
        },
      },
      {
        value: 'count',
        label: '商品数量',
        slot: true,
      },
      {
        value: 'salePrice',
        label: '出售价格',
        allSlot: true,
      },
      {
        value: 'status',
        label: '订单状态',
        type: 'el-select',
        props: {
          options: [
            { value: 0, label: '出货' },
            { value: 1, label: '进货' },
          ],
        },
      },
    ]

    const username = computed(() => store.getters.name)

    async function handleSubmit (data) {
      console.log('data', data.totalFee)
      const price = data.price * 100
      const salePrice = data.status < 1 ? data.salePrice * 100 : null
      const totalFee = data.totalFee * 100

      if (data.id) {
        await orderEdit({ ...data, price, salePrice, totalFee, userId: username.value })
      } else {
        await Promise.all([
          orderCreate({ ...data, price, salePrice, totalFee, userId: username.value }),
          orderCreate({ ...data, price, salePrice, totalFee, userId: username.value }),
          orderCreate({ ...data, price, salePrice, totalFee, userId: username.value }),
          orderCreate({ ...data, price, salePrice, totalFee, userId: username.value }),
          orderCreate({ ...data, price, salePrice, totalFee, userId: username.value }),
        ],
        )
      }
      emit('update:visible', false)
      emit('refresh')
      ElMessage.success('操作成功')
    }
    function handleCancel () {
      emit('update:visible', false)
    }

    const querySearchAsync = async (queryString: string, cb: (arg: any) => void) => {
      const data = await getGoodsList({ name: queryString }) as any
      cb(data.rows)
    }

    function handleSelect (item, data) {
      data.goodsId = item.id
      data.goodsName = item.name
      data.price = item.price
      data.unit = item.unit
      data.weight = item.weight
      data.goodsBrand = item.brand
      handleChange(data.count, data)
    }
    function handleChange (value, item) {
      const { price } = item
      if (!value || !price) {
        item.totalFee = null
      } else {
        item.totalFee = (value * price).toFixed(2)
      }
      console.log('value', value, item)
    }

    return {
      dialogVisible,
      fields,
      options,
      handleCancel,
      handleSubmit,
      querySearchAsync,
      handleSelect,
      handleChange,
    }
  },
})
</script>

<style scoped lang="less">
  :deep(.el-input-number .el-input__inner){
    text-align: left;
  }
</style>
